package com.ts.api.common.util;

import com.gitee.apanlh.util.base.Empty;
import com.gitee.apanlh.util.date.DateUtils;
import com.gitee.apanlh.util.date.parse.DateParser;
import com.gitee.apanlh.util.reflection.ClassConvertUtils;
import com.gitee.apanlh.util.valid.ValidParam;
import com.ts.api.module.channel.entity.po.ChannelMarketPO;
import com.ts.api.module.product.entity.po.ProductPlanPO;

import java.time.LocalTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 *  产品、贷超工具类
 *
 *  @author Pan
 */
public class OpenTimeUtils {

    /**
     *  过滤开放时间
     *
     *  @param list
     *  @param <T>
     */
    public static <T> List<T> filter(List<T> list) {
        if (ValidParam.isEmpty(list)) {
            return Empty.list();
        }
        return list.stream().filter(t -> hasOpen(t)).collect(Collectors.toList());
    }

    /**
     *  是否在开放时间之内
     *
     *  @param  t
     *  @param  <T>
     *  @return boolean true在范围时间之内
     */
    public static <T> boolean hasOpen(T t) {
        if (t == null) {
            return false;
        }

        //  贷超产品
        if (t instanceof ChannelMarketPO channelMarketPO) {
           return hasMarketOpen(channelMarketPO);
        }

        //  主体计划
        if (t instanceof ProductPlanPO productPlanPO) {
            return hasPlanOpen(productPlanPO);
        }
        return false;
    }

    /**
     *  当前贷超是否开放
     *
     *  @param  channelMarketPO 贷超对象
     *  @return boolean true当前开放
     */
    public static boolean hasMarketOpen(ChannelMarketPO channelMarketPO) {
        LocalTime now = LocalTime.now();

        String openTime = channelMarketPO.getOpenTime();
        //  时间格式:09:04-16:00
        String[] split = openTime.split("-");
        return (!now.isBefore(DateParser.getLocalTime(split[0] + ":00")) && !now.isAfter(DateParser.getLocalTime(split[1] + ":00")));
    }

    /**
     *  当前计划是否开放
     *
     *  @param  productPlanPO   主体计划对象
     *  @return boolean true当前开放
     */
    public static boolean hasPlanOpen(ProductPlanPO productPlanPO) {
        LocalTime now = LocalTime.now();

        //  星期判断
        String openDates = productPlanPO.getOpenDates();
        int currentDayOfWeek = DateUtils.getCurrentDayOfWeek();
        if (!openDates.contains(ClassConvertUtils.toStr(currentDayOfWeek))) {
            return false;
        }

        //  时间段判断
        String openTimes = productPlanPO.getOpenTime();
        String[] openTimesSplit = openTimes.split(";");
        for (String openTime : openTimesSplit) {
            String[] time = openTime.split("-");
            //  如果出现在时间范围内直接返回
            boolean isRange = !now.isBefore(DateParser.getLocalTime(time[0] + ":00")) && !now.isAfter(DateParser.getLocalTime(time[1] + ":00"));
            if (isRange) {
                return true;
            }
        }
        return false;
    }
}
